import '../../../common/common.dart';
import 'package:bundle_id_launch/bundle_id_launch.dart';

enum HomePageTaskType {
  /// 首页
  // home,

  /// 时刻
  scene,

  /// 设备
  devices,

  /// 应用
  application,
}

class HomePageMenu {
  final HomePageTaskType taskType;
  final String title;
  final String normalImage;
  final String selectedImage;

  HomePageMenu({
    required this.taskType,
    required this.title,
    required this.normalImage,
    required this.selectedImage,
  });
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late List<HomePageMenu> _menuList;
  HomePageTaskType _currentTaskType = HomePageTaskType.scene;

  _changeMenu({required HomePageMenu menu}) {
    var index = _menuList.indexOf(menu);
    setState(() {
      _currentTaskType = HomePageTaskType.values[index];
      _index = index;
    });
  }

  int _index = 0;
  final _appController = Get.find<AppController>();

  Future<void> _test() async {
    await _appController.refreshUserInfo();
    // var res = await _appController.refreshUserFamilyList();
    // var resOfToken = await ApiManager.downloadFile(url: 'https://meetingiot.oss-cn-beijing.aliyuncs.com/switcher/smart_insight/token');
    // if (resOfToken != null){
    //   debugPrint('---> _HomePageState._test resOfToken: ${resOfToken}');
    // }
  }

  @override
  void initState() {
    super.initState();
    _menuList = [
      // HomePageMenu(taskType: HomePageTaskType.home, title: '首页', normalImage: 'images/home/menu/home.png', selectedImage: 'images/home/menu/home_selected.png'),
      HomePageMenu(taskType: HomePageTaskType.scene, title: '时刻', normalImage: 'images/home/menu/scene.png', selectedImage: 'images/home/menu/scene_selected.png'),
      HomePageMenu(taskType: HomePageTaskType.devices, title: '设备', normalImage: 'images/home/menu/device.png', selectedImage: 'images/home/menu/device_selected.png'),
      HomePageMenu(taskType: HomePageTaskType.application, title: '应用', normalImage: 'images/home/menu/application.png', selectedImage: 'images/home/menu/application_selected.png'),
    ];
    // _initTencentSDK();
  }

  @override
  Widget build(BuildContext context) {
    Color _menuNormalColor = Colors.white;
    Color _menuSelectedColor = '#2AE9AE'.hexColor;

    Widget leftMenu = SizedBox(
      width: 160.r,
      // color: '#0D0D0D'.hexColor,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: _menuList.map((e) {
          Color color = e.taskType == _currentTaskType ? _menuSelectedColor : _menuNormalColor;
          String image = e.taskType == _currentTaskType ? e.selectedImage : e.normalImage;
          return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              _changeMenu(menu: e);
            },
            child: Column(
              children: [
                image.getImageWidget(
                  width: 48.r,
                  height: 48.r,
                ),
                SizedBox(height: 12.r),
                Text(
                  e.title,
                  style: TextStyle(fontSize: 20.sp, color: color),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
    List<Widget> rightContentChildren = [
      const ScenePage(),
      const HomeRoomDeviceListWidget(),
      _getAppWidget(),
    ];
    return Scaffold(
      body: Container(
        color: Colors.black,
        child: Stack(
          children: [
            Positioned.fill(
              child: Row(
                children: [
                  leftMenu,
                  Expanded(
                    child: IndexedStack(
                      index: _index,
                      children: rightContentChildren,
                    ),
                  ),
                ],
              ),
            ),
            Positioned(
              top: 0,
              left: 160.r,
              width: 80.w,
              bottom: 0,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Colors.black,
                      Colors.black.withOpacity(0.8),
                      Colors.transparent,
                    ],
                    stops: const [0, 0.3, 1],
                    tileMode: TileMode.clamp,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: kDebugMode
          ? FloatingActionButton(
        onPressed: () => _test(),
        child: const Text('D'),
      )
          : null,
    );
  }

  Widget _getAppWidget() {
    return Container(
      margin: EdgeInsets.only(left: 80.w, top: 67.h, right: 64.w, bottom: 160.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            "应用",
            style: TextStyle(fontSize: 40.sp, color: const Color.fromRGBO(255, 255, 255, 1)),
          ),
          SizedBox(height: 67.h),
          Expanded(child: _getAppItems()),
        ],
      ),
    );
  }

  Future<bool> _onClickAppByKey({required String key}) async {
    if (key == 'setting') await Get.toNamed(AppRoute.setting);
    if (key == 'com.knowin.weather') {
      var res = await BundleIdLaunch.launch(bundleId: key);
      debugPrint('---> _HomePageState._onClickAppByKey com.knowin.weather res: ${res}');
      if (!res) {
        Toast.show('请安装天气软件');
      }
    }
    if (key == 'com.tencent.qqmusiccar') {
      // var res = await BundleIdLaunch.launch(bundleId: key);
      // debugPrint('---> _HomePageState._onClickAppByKey com.tencent.qqmusiccar res: ${res}');
      // if (!res){
      //   Toast.show('请安装QQ音乐软件');
      // }
      Get.toNamed(AppRoute.qqMusicPage);
    }
    if (key == 'com.qiyi.video.speaker') {
      var res = await BundleIdLaunch.launch(bundleId: key);
      debugPrint('---> _HomePageState._onClickAppByKey com.qiyi.video.speaker res: ${res}');
      if (!res) {
        Toast.show('请安装爱奇艺软件');
      }
    }
    return true;
  }

  Widget _getAppItems() {
    List<Map<String, String>> appInfo = [
      {'key': 'com.knowin.weather', 'name': '天气', 'image': 'images/home/menu/icon_weather_logo.png'},
      {'key': 'com.tencent.qqmusiccar', 'name': 'QQ音乐', 'image': 'images/home/menu/icon_qq_music_car_logo.png'},
      {'key': 'com.qiyi.video.speaker', 'name': '爱奇艺', 'image': 'images/home/menu/icon_qiyi_logo.png'},
      {'key': 'setting', 'name': '设置', 'image': 'images/home/menu/icon_settings_logo.png'},
    ];
    var appGrid = NoShadowScrollConfiguration(
      child: GridView.builder(
        scrollDirection: Axis.horizontal,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 360 / 256,
          crossAxisSpacing: 16.h,
          mainAxisSpacing: 16.w,
        ),
        itemBuilder: (c, index) {
          var app = appInfo[index];
          var key = app['key'] ?? '';
          var name = app['name'] ?? '';
          var image = app['image'] ?? '';
          return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => _onClickAppByKey(key: key),
            child: Container(
              decoration: BoxDecoration(color: '#181B23'.hexColor, borderRadius: BorderRadius.circular(24.r)),
              child: Column(
                // mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(height: 40.h),
                  Text(
                    name,
                    style: TextStyle(fontSize: 28.sp, color: const Color.fromRGBO(255, 255, 255, 1)),
                  ),
                  SizedBox(height: 46.h),
                  SizedBox(
                    width: 146.r,
                    height: 146.r,
                    child: image.image,
                  ),
                ],
              ),
            ),
          );
        },
        itemCount: appInfo.length,
      ),
    );
    return appGrid;
  }
}